home *** CD-ROM | disk | FTP | other *** search
- Path: apoll.informatik.uni-bonn.de!Mars!schregle
- From: schregle@Mars (Roland Schregle)
- Newsgroups: comp.lang.c++
- Subject: Re: Virtual Base Class
- Date: 12 Mar 1996 16:46:20 GMT
- Organization: Rheinische Friedrich-Wilhelms-Universit"at Bonn, Institut
- Message-ID: <4i49os$20j@apoll.informatik.uni-bonn.de>
- References: <313F98D0.102E@ucla.edu> <4i1k92$3n8@apoll.informatik.uni-bonn.de>
- NNTP-Posting-Host: mars.informatik.uni-bonn.de
- X-Newsreader: TIN [version 1.2 PL2]
-
- Yep, I'm replying to myself...
-
- Roland Schregle (schregle@zeus.informatik.uni-bonn.de) wrote:
- : Dennis Rahaman (dennisr@ucla.edu) wrote:
- : : This is what I want to do:
-
- : : a
- : : / \
- : : b c
- : : \ /
- : : d
-
-
- : : class a
- : : {
- : : //...
- : : };
-
- : : class b : public virtual a
- : : {
- : : //...
- : : };
-
- : : class c : public virtual b
- Judging by the diagram, I would assume this class is derived from
- class a, NOT b.
- : : {
- : : //...
- : : };
-
- : : class d : public b, public c
- : : {
- : : //...
- : : };
-
-
- : : void f ()
- : : {
- : : a a1;
- : : d* pd = (d*) &a1; // error: can't cast virtual base to derived
- : : }
-
- : : ///////////////////////////////////////////////////////////
- : : Can someone explain why I can't cast a virtual base class to a derived
- : : class?
-
- : : What should I do instead?
-
- : : Any help would be appreciated.
-
-
-
- : I have the same problem! Somebody suggested the following (in terms of the
- : above egg sample):
-
- : void f()
- : {
- : a a1;
- : d* pd = (d*)(void*)&a1;
- : }
-
- : I haven't tried this yet. C'mon you C++ cracks out there!!! :)
-
-
- : GanjaTron
-
- Actually, GanjaTron, I *did* try it out, however it requires adding an
- offset to the void*:
-
- void f()
- {
- a a1;
- d* testy = new d; // :)
- int offset = (void*)testy - (void*)(a*)testy;
- delete testy;
- d* pd = (d*)((void*)a1 + offset);
- }
-
- The offset specifies the difference of the addresses where the instance
- of the derived class and that of the virtual base class within it are
- stored. (I didn't come up with this method, so correct me if I'm wrong
- or totally vague).
-
- This ALLEGEDLY works on most (all?) compilers, I only tried it with GNU.
- Needless to say, it's FILTHY code!
-
- So THERE, GanjaTron! :)
-
- GanjaTron
-